﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;

using DotNetARX;
using Autodesk.AutoCAD.Runtime;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoCADPlugin
{
    public class 几何解题
    {
        //已知四边形ABCD四个顶点的坐标为A(1,3),B(m,0),C(m+2,0),D(5,1),当四边形ABCD的周长最小时，m的值为多少？
        [CommandMethod("CalM")]
        public void CalM()
        {
            Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
            PromptDoubleResult Bianliang = ed.GetDouble("\n请输入m的值");
            double m = Bianliang.Value;
            Point3d A = new Point3d(1, 3, 0); Point2d AA = new Point2d(1, 3);
            Point3d B = new Point3d(m , 0, 0); Point2d BB = new Point2d(m , 0);
            Point3d C = new Point3d(m + 2, 0, 0); Point2d CC = new Point2d(m  + 2, 0);
            Point3d D = new Point3d(5, 1, 0); Point2d DD = new Point2d(5, 1);

            //画出四边形
            Polyline pl = new Polyline();
            pl.CreatePolyline(AA, BB, CC, DD);
            pl.Closed = true;
            Database db = HostApplicationServices.WorkingDatabase;
            using (var tr = db.TransactionManager.StartTransaction())
            {
                var id = db.AddToCurrentSpace(pl);
                tr.Commit();
            }

            //计算四边形的周长
            Line lineAB = new Line(A, B);
            Line lineBC = new Line(B, C);
            Line lineCD = new Line(C, D);
            Line lineAD = new Line(A, D);
            double Perimeter = LineLength(lineAB) + LineLength(lineBC) + LineLength(lineCD) + LineLength(lineAD);
            ed.WriteMessage($"\n该四边形的周长为{Perimeter}。");

        }
        /// <summary>
        /// 计算直线长度
        /// </summary>
        /// <param name="l"></param>
        /// <returns>直线长度</returns>
        public static double LineLength(Line l)
        {
            double c = (l.StartPoint.X - l.EndPoint.X) * (l.StartPoint.X - l.EndPoint.X) 
                     + (l.StartPoint.Y - l.EndPoint.Y) * (l.StartPoint.Y - l.EndPoint.Y);//勾股定理c^2=a^2+b^2
            return Math.Sqrt(c);
        }

    }
}
